﻿using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using Image = System.Drawing.Image;

public class WallpaperSetting : MonoBehaviour
{
    public string ImagePath;
    public int ResolutionX = 1920;
    public int ResolutionY = 1080;
    public Camera ShotCamera;
    public RenderTexture ShotRenderTexture;
    public VerticalLayoutGroup verticalLayoutGroup;
    public string ConfigPath;

    public RectTransform textRectTransform;
    public Text text;
    public float textW;
    public float textH;
    public int fontSize;
    private bool _showGui = true;
    private float _guiScale = 2;

    [ContextMenu("PlayerPrefs.DeleteAll")]
    public void DeleteAll()
    {
        PlayerPrefs.DeleteAll();
    }

    void Start()
    {
        //init
        ResolutionX = Screen.width;
        ResolutionY = Screen.height;
        ImagePath = Path.Combine(Application.streamingAssetsPath, "wallpaper.png");
        ShotRenderTexture = new RenderTexture(ResolutionX, ResolutionY, 24);
        ShotCamera.targetTexture = ShotRenderTexture;
        ConfigPath = Path.Combine(Application.streamingAssetsPath, "config.txt");
        fontSize = text.fontSize = PlayerPrefs.GetInt("default-fontSize", 45);
        textRectTransform.sizeDelta = new Vector2(PlayerPrefs.GetFloat("default-textW", 400),
            PlayerPrefs.GetFloat("default-textH", 200));
        textW = textRectTransform.sizeDelta.x;
        textH = textRectTransform.sizeDelta.y;
        LoadContent();
    }

    private void OnDestroy()
    {
        //save
        PlayerPrefs.SetInt("default-fontSize", fontSize);
        PlayerPrefs.SetFloat("default-textW", textW);
        PlayerPrefs.SetFloat("default-textH", textH);
        PlayerPrefs.Save();
    }

    IEnumerator TakeShot()
    {
        _showGui = false;
        yield return new WaitForEndOfFrame();
        RenderTexture tmp = RenderTexture.active;
        RenderTexture.active = ShotRenderTexture;
        yield return new WaitForEndOfFrame();
        Texture2D png = new Texture2D(ResolutionX, ResolutionY, TextureFormat.ARGB32, false);
        png.ReadPixels(new Rect(0, 0, ResolutionX, ResolutionY), 0, 0);
        byte[] bytes = png.EncodeToPNG();
        File.WriteAllBytes(ImagePath, bytes);
        _showGui = true;
    }


    private void LoadContent()
    {
        string[] allLine = File.ReadAllLines(ConfigPath);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < allLine.Length; i++)
        {
            sb.Append(allLine[i]);
            sb.Append("\n");
        }

        text.text = sb.ToString();
    }

    private void OnGUI()
    {
        if (!_showGui) return;

        Matrix4x4 tmp = GUI.matrix;
        GUI.matrix = Matrix4x4.Scale(new Vector3(_guiScale, _guiScale, _guiScale));

        GUILayout.BeginVertical("Box",GUILayout.Width(200));
        {
            if (GUILayout.Button("载入内容"))
            {
                LoadContent();
            }

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button("打开配置"))
                {
                    Process.Start(ConfigPath);
                }

                if (GUILayout.Button("打开配置目录"))
                {
                    string args = string.Format("/Select, {0}", Path.GetDirectoryName(ConfigPath));
                    args = args.Replace("/", "\\");
                    print(args);
                    ProcessStartInfo pfi = new ProcessStartInfo("Explorer.exe", args);
                    Process.Start(pfi);
                }
            }
            GUILayout.EndHorizontal();
            if (GUILayout.Button("生成壁纸"))
            {
                StartCoroutine(TakeShot());
            }

            if (GUILayout.Button("设置"))
            {
                SetDestPicture(ImagePath);
            }

            int curr = (int) GUILayout.HorizontalSlider(fontSize, 1, 100);
            if (fontSize != curr)
            {
                text.fontSize = fontSize;
            }

            fontSize = curr;

            float currf = GUILayout.HorizontalSlider(textW, 300, 1500);
            if (textW != currf)
            {
                textRectTransform.sizeDelta = new Vector2(textW, textH);
            }

            textW = currf;

            currf = GUILayout.HorizontalSlider(textH, 200, 1000);
            if (textH != currf)
            {
                textRectTransform.sizeDelta = new Vector2(textW, textH);
            }

            textH = currf;
        }
        GUILayout.EndVertical();

        GUI.matrix = tmp;
    }

    #region 设置壁纸

    [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
    public static extern int SystemParametersInfo(
        int uAction,
        int uParam,
        string lpvParam,
        int fuWinIni
    );

    private void SetDestPicture(string picture)
    {
        if (File.Exists(picture))
        {
            string ex = Path.GetExtension(picture).ToLower();
            if (ex != ".bmp")
            {
                // 其它格式文件先转换为bmp再设置
                string tempFile = Path.Combine(Application.streamingAssetsPath, "tmp.bmp");
                Image image = Image.FromFile(picture);
                image.Save(tempFile, System.Drawing.Imaging.ImageFormat.Bmp);
                picture = tempFile;
            }

            SystemParametersInfo(20, 0, picture, 0x2);
        }
    }

    #endregion
}